package com.shengqin.controller;

import com.shengqin.controller.api.dto.SchoolTestStatisticsDTO;
import com.shengqin.controller.api.dto.ProjectTestStatisticsDTO;
import com.shengqin.entity.Plan;
import com.shengqin.service.IPlanService;
import com.shengqin.service.ITestStatisticsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("/admin/statistics")
@Tag(name = "测试统计", description = "体质测试统计相关接口")
public class TestStatisticsController {

    @Autowired
    private ITestStatisticsService testStatisticsService;
    @Autowired
    private IPlanService planService;

    @GetMapping("/school")
    @Operation(summary = "获取学校测试统计数据")
    public List<SchoolTestStatisticsDTO> getSchoolStatistics(
            @Parameter(description = "计划ID", required = true) @RequestParam Integer planId,
            @Parameter(description = "学校ID（可选）") @RequestParam(required = false) Integer schoolId) {
        return testStatisticsService.getSchoolTestStatistics(planId, schoolId);
    }

    @GetMapping("/report/pdf")
    @Operation(summary = "下载测试统计PDF报告")
    public ResponseEntity<byte[]> generatePdfReport(
            @Parameter(description = "计划ID", required = true) @RequestParam Integer planId,
            @Parameter(description = "学校ID（可选）") @RequestParam(required = false) Integer schoolId) throws UnsupportedEncodingException {
        byte[] pdfContent = testStatisticsService.generateTestStatisticsPDF(planId, schoolId);

        Plan plan = planService.getById(planId);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_PDF);
        String fileName = URLEncoder.encode(plan.getName() + "分析报告.pdf", "UTF-8").replaceAll("\\+", "%20");
        headers.setContentDisposition(ContentDisposition.builder("attachment")
                .filename(fileName)
                .build());
        
        return new ResponseEntity<>(pdfContent, headers, HttpStatus.OK);
    }

    @GetMapping("/project")
    @Operation(summary = "获取项目测试统计数据")
    public List<ProjectTestStatisticsDTO> getProjectStatistics(
            @Parameter(description = "计划ID", required = true) @RequestParam Integer planId,
            @Parameter(description = "学校ID（可选）") @RequestParam(required = false) Integer schoolId) {
        return testStatisticsService.getProjectTestStatistics(planId, schoolId);
    }
} 